<?php

namespace App\Console\Commands;

use App\Logging\Service\LogCmdService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

abstract class BaseCommand extends Command
{
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 初始化日志
     * @author Chris Yu <chrisyu@crabapple.top> 2024/11/8
     */
    private function initLog()
    {
        // 设置通道为“cmd”需要的参数
        LogCmdService::getInstance()
            ->setCmdName($this->getName())
            ->setCmdFullName($this->getFullCmd())
            ->setCmdClass(static::class);

        // 设置默认的日志驱动为 cmd
        /* @var $logManager \Illuminate\Log\LogManager */
        $logManager = Log::getFacadeRoot();
        $logManager->setDefaultDriver('cmd');
    }

    /**
     * 导入客户
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->initLog();

        $this->infoLog("命令[{$this->getName()}]开始", ['cmdFullName' => $this->getFullCmd()]);

        $this->handleExec();

        $this->infoLog("命令[{$this->getName()}]开始");
    }

    abstract protected function handleExec();

    /**
     * 获取完整命令
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2024/3/25
     */
    protected function getFullCmd()
    {
        $cmd = $this->getName();
        $options = $this->options();
        $arguments = $this->arguments();

        foreach ($arguments as $key => $value) {
            if ($key === 'command') {
                continue;
            }
            $cmd .= " $value";
        }

        foreach ($options as $key => $value) {
            $cmd .= " --$key=$value";
        }

        return 'php artisan ' . $cmd;
    }

    public function debugLog($msg, $context = [])
    {
        $this->debug($msg);
        Log::debug($msg, $context);
    }

    public function infoLog($msg, $context = [])
    {
        $this->info($msg);
        Log::info($msg, $context);
    }

    public function errorLog($msg, $context = [])
    {
        $this->error($msg);
        Log::error($msg, $context);
    }

    public function noticeLog($msg, $context = [])
    {
        $this->notice($msg);
        Log::notice($msg, $context);
    }

    public function warningLog($msg, $context = [])
    {
        $this->warning($msg);
        Log::warning($msg, $context);
    }
}
